import { createRouter, createWebHistory } from 'vue-router';
import routes from './staticRouter';
import { getToken, getSessionToken } from "@/utils/token";
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import TagsAndBreadStore from '@/stores/modules/TagsAndBreadStore';
import RoutesStore from '@/stores/modules/RoutesStore';
import { DynamicRoutes } from '@/Apis'

const whiteList = ['/login']

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes
})

router.beforeEach(async (to, from, next) => {
    const token = getToken("token") || getSessionToken('token');
    const store = RoutesStore();
    NProgress.start();

    if (token) {
        if (to.path === '/login') {
            next({ path: '/' });
            NProgress.done()
        } else if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            if (store.addRoutes.length === 0) {
                // 获取动态路由数据
                await DynamicRoutes.Normal().then((res) => {
                    const info = res.data.data
                    store.Info(info);
                    store.AddRoutes(info);
                    // 循环组建动态路由
                    for (const routes of store.addRoutes) {
                        router.addRoute('Layout', routes);
                    }

                    router.addRoute({
                        path: '/:catchAll(.*)',
                        redirect: '/404'
                    });

                    next({ ...to, replace: true })
                })
                    .catch((error) => {
                        next();
                    })
            } else {
                next();
            }
        }
    } else {
        // 没有token
        if (whiteList.indexOf(to.path) !== -1) {
            // 在免登录白名单，直接进入
            next()
        } else {
            next(`/login?redirect=${encodeURIComponent(to.fullPath)}`) // 否则全部重定向到登录页
            NProgress.done()
        }
    }
});


router.afterEach((to, from) => {
    const tagsAndbreadStore = TagsAndBreadStore();
    // 面包屑导航
    const data = to.matched.map(({ path, meta: { title } }) => ({ link: path, text: title }));
    tagsAndbreadStore.BreadCrumb(data);

    // 标签导航栏
    if (to.path !== '/login') {
        tagsAndbreadStore.Tags({ path: to.path, title: to.meta.title, type: 'plain', isClose: true });
    }

    // 将所有路由的 type 修改为 'plain'
    tagsAndbreadStore.tags.forEach(tag => {
        tag.type = 'plain';
    });

    // 修改当前路由对应的 type 为 'dark'
    const targetTag = tagsAndbreadStore.tags.find(tag => tag.path === to.path);
    if (targetTag) {
        targetTag.type = 'dark';
    }

    NProgress.done();
})

export default router;
